package com.dsbj.icardservice.controller;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/sa")
public class AdminController extends BaseController {


	/**修改日志级别接口
	 * loglevel 级别对应关系 (ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF)
	*
	*
	* */
	@RequestMapping("/{type}/changeLogLevel/{logLevel}")
	@ResponseBody
	public String adjustLogLevel(@PathVariable(name = "type") String type, @PathVariable(name = "logLevel") String logLevel) {
		String levelStr = "INFO";
		Level level = Level.INFO;
		org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
		Configuration config = ctx.getConfiguration();
		LoggerConfig loggerConfig = getLoggerConfigByType(config,type);
		if(loggerConfig == null){
			return "日志类型不正确，请设置root 或 mybatis";
		}
		switch (logLevel){
			case "DEBUG":
				level = Level.DEBUG;
				levelStr = "DEBUG";
				break;
			case "INFO":
				level = Level.INFO;
				levelStr = "INFO";
				break;
			default:break;
		}
		loggerConfig.setLevel(level);
		ctx.updateLoggers();
		return type+" 日志级别修改成功,当前日志级别为: "+levelStr;
	}

	private LoggerConfig getLoggerConfigByType(Configuration config, String type) {
		switch (type){
			case "root":return config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
			case "mybatis":return config.getLoggerConfig("com.dsbj.icardservice.mapper");
			default:return null;
		}
	}


	@RequestMapping("/showLogLevel")
	@ResponseBody
	public String showLogLevel() {
		org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
		Configuration config = ctx.getConfiguration();
		LoggerConfig loggerConfig = getLoggerConfigByType(config,"root");
		StringBuilder sb = new StringBuilder();
		sb.append("当前日志级别: ").append("<br/>");
		sb.append("root: ").append(loggerConfig.getLevel().name()).append("<br/>");
		loggerConfig = getLoggerConfigByType(config,"mybatis");
		sb.append("mybatis: ").append(loggerConfig.getLevel().name()).append("<br/>");
		return sb.toString();
	}


}
